package com.farm.project.service.impl;

import com.farm.project.domain.Project;
import com.farm.project.domain.Projectuser;
import com.farm.project.domain.Task;
import com.farm.project.domain.Taskuser;
import com.farm.core.time.TimeTool;
import org.apache.log4j.Logger;

import com.farm.project.dao.TaskDaoInter;
import com.farm.project.dao.TaskuserDaoInter;
import com.farm.project.service.ProjectuserServiceInter;
import com.farm.project.service.TaskuserServiceInter;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBRuleList;
import com.farm.core.sql.query.DataQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.farm.authority.domain.User;
import com.farm.core.auth.domain.LoginUser;

/* *
 *功能：任务干系人服务层实现类
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@Service
public class TaskuserServiceImpl implements TaskuserServiceInter {
	@Resource
	private TaskuserDaoInter taskuserDaoImpl;
	@Resource
	private TaskDaoInter taskDaoImpl;
	@Resource
	private ProjectuserServiceInter projectUserServiceImpl;

	private static final Logger log = Logger.getLogger(TaskuserServiceImpl.class);

	@Override
	@Transactional
	public Taskuser insertTaskuserEntity(Taskuser entity, LoginUser user) {
		// TODO 自动生成代码,修改后请去除本注释
		// entity.setCuser(user.getId());
		// entity.setCtime(TimeTool.getTimeDate14());
		// entity.setCusername(user.getName());
		// entity.setEuser(user.getId());
		// entity.setEusername(user.getName());
		// entity.setEtime(TimeTool.getTimeDate14());
		// entity.setPstate("1");
		return taskuserDaoImpl.insertEntity(entity);
	}

	@Override
	@Transactional
	public Taskuser editTaskuserEntity(Taskuser entity, LoginUser user) {
		// TODO 自动生成代码,修改后请去除本注释
		Taskuser entity2 = taskuserDaoImpl.getEntity(entity.getId());
		// entity2.setEuser(user.getId());
		// entity2.setEusername(user.getName());
		// entity2.setEtime(TimeTool.getTimeDate14());
		entity2.setLivetime(entity.getLivetime());
		entity2.setPoptype(entity.getPoptype());
		entity2.setTaskid(entity.getTaskid());
		entity2.setUserid(entity.getUserid());
		entity2.setPstate(entity.getPstate());
		entity2.setProjectid(entity.getProjectid());
		entity2.setPcontent(entity.getPcontent());
		entity2.setCuser(entity.getCuser());
		entity2.setCtime(entity.getCtime());
		entity2.setId(entity.getId());
		taskuserDaoImpl.editEntity(entity2);
		return entity2;
	}

	@Override
	@Transactional
	public void deleteTaskuserEntity(String id, LoginUser user) {
		Taskuser taskuser = getTaskuserEntity(id);
		List<Taskuser> admins = taskuserDaoImpl.selectEntitys(DBRuleList.getInstance()
				.add(new DBRule("TASKID", taskuser.getTaskid(), "=")).add(new DBRule("POPTYPE", "1", "=")).toList());
		if (admins.size() == 1 && admins.get(0).getUserid().equals(taskuser.getUserid())) {
			// 只有一个管理员且当前用户是唯一管理员，则不能修改
			throw new RuntimeException("无法删除唯一管理员");
		}
		taskuserDaoImpl.deleteEntity(taskuserDaoImpl.getEntity(id));
	}

	@Override
	@Transactional
	public Taskuser getTaskuserEntity(String id) {
		// TODO 自动生成代码,修改后请去除本注释
		if (id == null) {
			return null;
		}
		return taskuserDaoImpl.getEntity(id);
	}

	@Override
	@Transactional
	public DataQuery createTaskuserSimpleQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery.init(query, "PLOGS_TASK_USER a left join ALONE_AUTH_USER b on a.userid=b.id",
				"a.ID as ID,a.LIVETIME as LIVETIME,a.POPTYPE as POPTYPE,a.TASKID as TASKID,a.USERID as USERID,a.PSTATE as PSTATE,a.PROJECTID as PROJECTID,a.PCONTENT as PCONTENT,a.CUSER as CUSER,a.CTIME as CTIME,B.NAME AS USERNAME,B.LOGINNAME AS LOGINNAME");
		return dbQuery;
	}

	@Override
	@Transactional
	public void resetTasktuser(String taskid, LoginUser currentUser) {
		Task task = taskDaoImpl.getEntity(taskid);
		taskuserDaoImpl.deleteEntitys(DBRuleList.getInstance().add(new DBRule("userid", task.getCuser(), "="))
				.add(new DBRule("taskid", taskid, "=")).toList());
		adduser(taskid, task.getCuser(), "1", currentUser, false);
	}

	@Override
	@Transactional
	public void adduser(String taskid, String userid, String poptype, LoginUser currentUser, boolean isFreshLivetime) {
		Task task = taskDaoImpl.getEntity(taskid);
		if (isFreshLivetime) {
			projectUserServiceImpl.refreshLivetime(task.getProjectid(), userid);
		}
		if (taskuserDaoImpl.selectEntitys(DBRuleList.getInstance().add(new DBRule("userid", userid, "="))
				.add(new DBRule("taskid", taskid, "=")).toList()).size() <= 0) {
			Taskuser entity = new Taskuser();
			entity.setCuser(currentUser.getId());
			entity.setCtime(TimeTool.getTimeDate14());
			entity.setLivetime(TimeTool.getTimeDate14());
			entity.setPoptype(poptype);
			entity.setProjectid(task.getProjectid());
			entity.setUserid(userid);
			entity.setTaskid(taskid);
			entity.setPstate("1");
			taskuserDaoImpl.insertEntity(entity);
		}
	}

	@Override
	@Transactional
	public List<Taskuser> getTaskUser(String taskId, String poptype) {
		return taskuserDaoImpl.selectEntitys(DBRuleList.getInstance().add(new DBRule("poptype", poptype, "="))
				.add(new DBRule("taskid", taskId, "=")).toList());
	}

	@Override
	@Transactional
	public void bindDoUser(String taskId, String userId, LoginUser currentUser) {
		Task task = taskDaoImpl.getEntity(taskId);
		projectUserServiceImpl.refreshLivetime(task.getProjectid(), userId);
		List<Taskuser> taskUsers = taskuserDaoImpl.selectEntitys(DBRuleList.getInstance()
				.add(new DBRule("userid", userId, "=")).add(new DBRule("taskid", taskId, "=")).toList());
		for (Taskuser taskUser : taskUsers) {
			if (taskUser.getPoptype().equals("1")) {
				// 删除当前执行人
				taskuserDaoImpl.deleteEntitys(DBRuleList.getInstance().add(new DBRule("POPTYPE", "2", "="))
						.add(new DBRule("TASKID", taskId, "=")).toList());
				return;
			}
		}
		{// 删除任务执行人
			taskuserDaoImpl.deleteEntitys(DBRuleList.getInstance().add(new DBRule("POPTYPE", "2", "="))
					.add(new DBRule("TASKID", taskId, "=")).toList());
			// 删除当前执行人
			taskuserDaoImpl.deleteEntitys(DBRuleList.getInstance().add(new DBRule("USERID", userId, "="))
					.add(new DBRule("TASKID", taskId, "=")).toList());
			Taskuser entity = new Taskuser();
			entity.setCuser(currentUser.getId());
			entity.setCtime(TimeTool.getTimeDate14());
			entity.setLivetime(TimeTool.getTimeDate14());
			entity.setPoptype("2");
			entity.setProjectid(task.getProjectid());
			entity.setUserid(userId);
			entity.setTaskid(taskId);
			entity.setPstate("1");
			taskuserDaoImpl.insertEntity(entity);
		}
	}

	@Override
	@Transactional
	public boolean isDoUser(String taskId, LoginUser currentUser) {
		List<Taskuser> taskUsers = taskuserDaoImpl.selectEntitys(DBRuleList.getInstance()
				.add(new DBRule("taskid", taskId, "=")).add(new DBRule("POPTYPE", "2", "=")).toList());
		if (taskUsers.size() > 0) {
			// 有执行人
			for (Taskuser taskUser : taskUsers) {
				if (taskUser.getUserid().equals(currentUser.getId())) {
					// 是执行人
					return true;
				}
			}
			// 不是执行
			return false;
		} else {
			// 沒有执行人
			return isManagerUser(taskId, currentUser);
		}
	}

	@Override
	@Transactional
	public boolean isManagerUser(String taskId, LoginUser currentUser) {
		List<Taskuser> taskUsers = taskuserDaoImpl.selectEntitys(DBRuleList.getInstance()
				.add(new DBRule("userid", currentUser.getId(), "=")).add(new DBRule("taskid", taskId, "=")).toList());
		for (Taskuser taskUser : taskUsers) {
			if (taskUser.getPoptype().equals("1")) {
				return true;
			}
		}
		return false;
	}

	@Override
	@Transactional
	public List<Map<String, Object>> getTaskUsers(String taskId) throws SQLException {
		DataQuery query = DataQuery.getInstance(1, "A.POPTYPE as POPTYPE,b.NAME as USERNAME,b.ID as USERID",
				"PLOGS_TASK_USER a left join ALONE_AUTH_USER b on a.userid=b.id");
		query.addRule(new DBRule("TASKID", taskId, "="));
		query.setPagesize(100);
		return query.search().getResultList();
	}
}
